import { useState, useEffect } from "preact/hooks";
import { engineKeywords } from "../engines";
import { copyText, stopPropagation } from "../utilities";

const EngineCode = ({ eurl, theme }) => {
  const [group, setGroup] = useState([]);
  useEffect(() => {
    const data = [];
    for (const currentFlag of engineKeywords) {
      let position = 0;
      let flagPos = 0;
      if (eurl.includes(currentFlag)) {
        while ((flagPos = eurl.indexOf(currentFlag, position)) >= 0) {
          if (flagPos > position) {
            data.push([eurl.slice(position, flagPos), false]);
          }
          data.push([currentFlag, true]);
          position = flagPos + currentFlag.length;
        }
        if (position < eurl.length) {
          data.push([eurl.slice(position), false]);
        }
        setGroup([...data]);
        break;
      }
    }
    if (data.length === 0) {
      setGroup([[eurl, false]]);
    }
  }, [eurl]);

  return (
    <button
      class="inline appearance-none"
      onClick={(event) => {
        stopPropagation(event);
        copyText(eurl);
      }}
    >
      <code>
        {group.map(([word, isKeyword], index) => (
          <span key={index} class={isKeyword ? theme : ""}>
            {word}
          </span>
        ))}
      </code>
    </button>
  );
};

export default EngineCode;
